import actionsType from "./actionsType"
const initState = {
  bookList: [],
  group: []
}
const reducer = (state = initState, action) => {
  const { type, payload } = action
  let { bookList, group } = state
  switch(type) {
    // 设置列表
    case actionsType.SET_BOOK_LIST:
      return {
        ...state,
        bookList: payload
      };
    // 切换状态
    case actionsType.SWITCH_CHECKED:
      const item = bookList.find(v => v.id === payload.id)
      item.isChecked = !item.isChecked
      
      return {
        ...state,
        bookList: [...bookList]
      };
    // 添加分组
    case actionsType.ADD_GROUP: 
      group.push(payload)
      return {
        ...state,
        group: [...group]
      };
    case actionsType.SET_GROUP: 
      const id = payload.id
      const groupItem = group.find(item => item.id === id)
      bookList.forEach(v => {
        v.isChecked && groupItem.list.push(v)
      })
      bookList = bookList.filter(item => !item.isChecked)
      return {
        ...state,
        bookList: [...bookList],
        group: [...group]
      }
    default: 
      return { ...state }
  }
}


export default reducer